$(async function () {
    var user = getcookie("lgc")
    if (getcookie("lgc")) {
        $(".show").css({ display: "none" }).removeClass()
        $(".hide").css({ display: "block" })
        $(".hide a").eq(0).html(`欢迎你:${getcookie("lgc")}`)
    }
    else {
        location.href = "./login_account.html?returnrul=" + encodeURIComponent(location.href)
    }


    $(".a1").click(function () {
        deletecookie("lgc")
        location.href = "./index.html"
    })

    $(document).on("click", ".shopping", function () {
        var url = urlParse();
        var { returnrul } = url;
        if (returnrul) {
            location.href = decodeURIComponent(returnrul);
        } else {
            location.href = "./index.html";
        }
    })

    var result = await searchshopcar({ user });
    var { status, msg, sql } = result;
    if (status) {
        var html = "";
        sql.forEach(({ id, goodsName, goodsImg, goodsPrice, buynum, total }) => {
            html += `<div class="list-item" data-index=${id}>
            <div class="col col-check">
                <label>
                    <input type="checkbox" class="check-one">
                </label>
            </div>
            <div class="col col-img">
                <img src="https:${goodsImg}"
                    alt="">
            </div>
            <div class="col col-detail"  title="${goodsName}">
                ${goodsName}</div>
            <div class="col col-price">${goodsPrice}元</div>
            <div class="col col-count">
                <div class="countBox">
                    <span class="reduce"></span>
                    <span class="countSpan">${buynum}</span>
                    <span class="add">+</span>
                </div>
            </div>
            <div class="col col-subtotal">${total}元</div>
            <div class="col col-operate"><i class="iconfont icon-close delete"></i></div>
        </div>`
        });
        $(".list-body").html(html);
    } else {
        alert(msg)
    }


    $(".reduce").each(function () {
        if ($(this).next().html() > 1) {
            $(this).html("-")
        }
    })

    $(".totalNum").html($(".list-item").length)


    $(".cart-wrap").click(async function (event) {
        var event = event || window.event;
        var target = event.target || event.srcElement;
        if (target.className == "check-all") {
            var status = $(target).prop("checked")
            $(".check-one").prop("checked", status)
            total();
            selecttoatl()
        }
        else if (target.className == "check-one") {
            var flag = $(".check-one").is(":not(:checked)")//是否存在未被选中的(true:存在,false:不存在)
            $(".check-all").prop("checked", !flag)
            total();
            selecttoatl()
        }
        else if (target.className == "add") {
            var num = $(target).prev().html()
            num++;
            $(target).prev().html(num)
            var price = parseFloat($(target).parent().parent().prev().html()) * 1
            var subtotal = (num * price).toFixed(2)
            $(target).parent().parent().next().html(subtotal + "元")
            $(target).prev().prev().html("-")
            var id = $(target).parents(".list-item").attr("data-index")
            var result = await goods_update({ id, buynum: num })
            total();
            selecttoatl()
        }
        else if (target.className == "reduce") {
            var num = $(target).next().html()
            if (num == 1) {
                return false
            }
            num--;
            $(target).next().html(num)
            var price = parseFloat($(target).parent().parent().prev().html()) * 1
            var subtotal = (num * price).toFixed(2)
            $(target).parent().parent().next().html(subtotal + "元")
            var id = $(target).parents(".list-item").attr("data-index")
            var result = await goods_update({ id, buynum: num })
            if (num == 1) {
                $(target).html("")
            }
            total();
            selecttoatl()
        }
        else if (target.classList.contains("delete")) {
            var item = confirm("是否删除当前商品");
            if (item) {
                var id = $(target).parents(".list-item").attr("data-index")
                var result = await goods_delete({ id });
                console.log(result);
                var { status, msg } = result;
                if (status) {
                    $(target).parents(".list-item").remove();
                } else {
                    alert(msg)
                }
                isallcheck();
                total();
                selecttoatl();
                jiesuanfn();
            }
        }
        else if (target.className == "delset") {
            if ($(".check-one:checked").length > 0) {
                if (confirm("是否删除选中的商品")) {
                    var arr = []
                    $(".check-one:checked").each(function () {
                        var id = $(this).parents(".list-item").attr("data-index")
                        arr.push(id)
                    })
                    var userid = arr.join()
                    console.log(userid);
                    var result = await goods_delete({ id: userid });
                    var { status, msg } = result;
                    if (status) {
                        $(".check-one:checked").parents(".list-item").remove()
                    } else {
                        alert(msg)
                    }
                    isallcheck()
                    total();
                    selecttoatl();
                    jiesuanfn();
                }
            } else {
                alert("你还未选中任何商品")
            }
        }
        else if (target.className == "delall") {
            if ($(".check-one").length) {
                if (confirm("是否删除全部商品")) {
                    var arr = []
                    $(".check-one").each(function () {
                        var id = $(this).parents(".list-item").attr("data-index")
                        arr.push(id)
                    })
                    var userid = arr.join()
                    console.log(userid);
                    var result = await goods_delete({ id: userid });
                    var { status, msg } = result;
                    if (status) {
                        $(".check-one:checked").parents(".list-item").remove()
                    } else {
                        alert(msg)
                    }
                    isallcheck()
                    total()
                    selecttoatl();
                    jiesuanfn();
                }
            } else {
                alert("没有任何商品了!")
            }
        }
        else if (target.className == "jiesuan") {
            if ($(".selectedTotal").html() * 1 == 0) {
                return false;
            }
            var t1 = confirm(`共${$(".selectedTotal").html()} 元, 是否结算 ? `)
            if (t1) {
                alert(`成功支付${$(".selectedTotal").html()} 元`)
                $(".check-all").prop("checked", false)
                $(".selectedNum").html(0)
                $(".check-one").each(function () {
                    $(this).prop("checked", false);
                    $(".countSpan").html(1)
                    var pricesub = parseFloat($(this).parents(".list-item").find(".col-price").text())
                    $(this).parents(".list-item").find(".col-subtotal").html(pricesub.toFixed(2) + "元")

                })
            }
            jiesuanfn();
        }
    })

    function isallcheck() {
        var flag = $(".check-one").is(":not(:checked)")//是否存在未被选中的(true:存在,false:不存在)
        $(".check-all").prop("checked", $(".check-one").length == 0 ? false : !flag);
    }

    function total() {
        var allprice = 0
        $(".check-one:checked").each(function () {
            var subtotal = parseFloat($(this).parents(".list-item").find(".col-subtotal").html()) * 1
            allprice += subtotal
        })
        $(".selectedTotal").html(allprice.toFixed(2))
        if ($(".selectedTotal").html() * 1 > 0) {
            $("#col-total").css({ background: "#ff6700" })
            $(".totalTips").css({ display: "none" })
        }
    }

    function selecttoatl() {
        var num = 0
        $(".check-one").each(function () {
            if ($(this).prop("checked")) {
                num += 1;
            }
        })
        $(".selectedNum").html(num)

        var totalNum = $(".check-one").length
        $(".totalNum").html(totalNum)

    }

    function jiesuanfn() {
        flag = true;
        $(".check-one").each(function () {
            if ($(this).prop("checked")) {
                flag = false;
            }
        })
        if (flag) {
            $(".selectedTotal").html("0.00");
            $("#col-total").css({ background: "#e0e0e0" })
            $(".totalTips").css({ display: "block" })
        }
    }
})


function urlParse() {
    var search = location.search;
    var data = {};
    if (search) {  //从注册页跳转过来  => 有数据
        var str = search.substring(1);
        var list = str.split("&");
        // console.log(list);
        list.forEach(function (item) {
            var key = item.split("=")[0];
            var val = item.split("=")[1];
            data[key] = val;
        })
    }
    return data;
}
